package com.puccampinas.finalproject.core.persistence.jdbc;

import java.sql.DriverManager;
import java.sql.SQLException;
import java.util.Properties;

import javax.sql.DataSource;

import org.apache.commons.dbcp.BasicDataSource;
import org.apache.commons.dbcp.BasicDataSourceFactory;

public final class DataSourceProvider {

	private DataSource dataSource;

	private static DataSourceProvider instance = new DataSourceProvider();

	private Properties properties;

	public static void init(Properties properties) {
    	instance.properties = properties; 
    }

	public static DataSourceProvider getInstance() {
		return instance;
	}

	public synchronized DataSource getDataSource() {

		if (dataSource == null) {
			try {

				dataSource = BasicDataSourceFactory.createDataSource(properties);

			} catch (Exception e) {
				
				throw new RuntimeException(
						"Problem on create database connection pool (DataSource)",
						e);
			}
		}
		
		return dataSource;
	}

	public static void undeployDriver() throws SQLException {
		DriverManager.deregisterDriver(DriverManager
				.getDriver(((BasicDataSource) instance.dataSource).getUrl()));
	}
}
